<template>
  <div class="action-app-form">
    <div class="action-app-form-item">
      <div class="title">{{ $t('common.connector.selectApplication') }}</div>
      <!-- <el-select
        v-model="app.data.appId"
        filterable
        :placeholder="$t('common.base.pleaseSelect')"
        style="width:100%;"
      >
        <el-option
          v-for="item in moduleList"
          :key="item.appId"
          :value="item.appId"
          :label="item.name"
        ></el-option>
      </el-select> -->
      <search-tree
        :current-node-key="app.data.appId"
        :tree-data="moduleList"
        :default-props="appTreeDefaultProps"
        :is-trigger="true"
        @select="handleTreeSelect"
      >
      </search-tree>
    </div>
    <div class="action-app-form-item">
      <div class="title">{{ $t('trigger.text1') }}</div>
      <search-tree
        :current-node-key="app.data.bizTypeAndId"
        :tree-data="apiList"
        :default-props="treeDefaultProps"
        :is-trigger="true"
        @select="handleTreeSelect"
      >
      </search-tree>
      
    </div>
      <!-- <trigger-drawer
          ref="triggerDrawerDom"
          v-if="app.type == 1"
          :nodeConfig.sync="app"
          :moduleList="moduleList"
          :parent="parent"
        /> -->

    <trigger-content :key="triggerContentKey" :node-config.sync="app"  :module-list="moduleList" :parent="app" ref="triggerDrawerDom"></trigger-content>

  </div>
</template>
<script>
import _ from 'lodash';
import SearchTree from '@src/component/form/components/FormConnector/SearchTree/SearchTree.vue';
import triggerContent from './trigger.vue';
import * as triggerApi from '@src/modules/connector/api/trigger';
import { uuid } from '@src/util/lang/string'
import { flowStore } from '@src/modules/connector/view/setting/components/workflow/store'
export default {
  name:'StartAppDrawer',
  props:{
    nodeConfig:{
      type:Object,
      default:()=>({})
    },
    moduleList:{
      type:Array,
      default:()=>([])
    }
  },
  computed:{
    originAppId() {
      return this.originNodeConfig?.data?.appId || ''
    },
    originBizTypeId() {
      return this.originNodeConfig?.data?.bizTypeId || ''
    },
    originTrigger() {
      return this.originNodeConfig?.childNodes?.data
    }, 
    originNodeChildNodes() {
      return this.originNodeConfig?.childNodes
    }
  },
  watch:{
    nodeConfig:{
      handler(newVal){
        this.app = newVal
      },
      deep:true,
      immediate:true
    },
    'app.data.appId':{
      handler(newVal, oldVal){
        // 发起应用变了 就将api清空
        if(newVal && newVal != oldVal) {
          // const app = this.moduleList.find(item => item.appId == newVal)
          const app = this.getAppByAppId(newVal)
          if(!app) return
          this.getApiList(app)
          if(oldVal) {
            this.app.data.bizType = ''
            this.app.data.bizTypeId = ''
            this.app.data.bizTypeAndId = ''
            this.$emit('update:nodeConfig', this.app)
          }
        }
      },
      deep:true,
      immediate:true
    },
    'app.data.bizTypeId':{
      handler(newVal){
        // 发起应用的api变了 就将触发器清空
        if(newVal && this.originBizTypeId) {
          if(newVal == this.originBizTypeId) {
            this.app.childNodes = this.originNodeChildNodes
            this.$emit('update:nodeConfig', this.app)
          } else {
            this.initTriggerInfo()
          }
          // console.log('drawer startApp bizTypeId', newVal, this.app)
        } else {
          // 发起应用的api被清空后就将触发器清空
          this.initTriggerInfo()
        }
      },
      deep:true,
      immediate:true
    },
  },
  data(){
    return{
      triggerContentKey: uuid(),
      loading: false,
      app:this.nodeConfig,
      appTreeDefaultProps:{
        children: 'children',
        label: 'name',
        key: 'appId',
      },
      treeDefaultProps:{
        children: 'children',
        label: 'name',
        key: 'bizTypeAndId',
      },
      apiList: [],
      originNodeConfig: _.cloneDeep(this.nodeConfig),
    }
  },
  methods:{
    getAppByAppId(targetAppId) {
      for (let i = 0; i < this.moduleList.length; i++) {
        const item = this.moduleList[i];
        if (item.children?.length) {
          const appItem = item.children.find(i =>i.appId == targetAppId)
          if(appItem) return appItem;
        }
      }
      return null;
    },
    initTriggerInfo() {
      this.app.childNodes.data = {
        bizActionCode: '',
        bizActionName: '',
        paasNodeId: '',
        url: '',
      }
      this.app.childNodes.childNodes = []
      this.$emit('update:nodeConfig', this.app)
    },
    getApiList(app) {
      const p = {
        appId: app.appId,
        direction: 'from',
      }
      triggerApi.getModuleListV2(p).then(res=>{
        // 处理数据跟以前保持一致
        if(res.status != 0) {
          this.apiList = []
          this.$message.warning(res.message || '')
          return
        }
        this.apiList = this.recursiveList(res.data, app)
      })
    },
    recursiveList(moduleList, app) {
      return moduleList.map(item => {
        item.appId = app.appId;
        item.appBizType = app.bizType;
        item.logo = app.logo;
        item.inside = app.inside;
        item.bizTypeId = item.id;
        item.bizTypeAndId = `${item.bizType},${item.bizTypeId}`;
        if(item?.children?.length) {
          item.children = this.recursiveList(item.children, app);
        }
        return item;
      });
    },
    handleTreeSelect(val){
      let data = {
        appId: '',
        appBizType: '',
        inside: true,
        name: '',
        logo: '',
        bizType: '',
        bizTypeId: '',
        bizTypeAndId: '',
      }
      if(val){
        let {appId, appBizType, inside, name, logo, bizType, bizTypeId, bizTypeAndId} = val
        data = {appId, appBizType, inside, name, logo, bizType, bizTypeId, bizTypeAndId}
        if(bizTypeId !== this.originBizTypeId) this.app.childNodes = []
      }
      this.app.data = data
      this.$emit('update:nodeConfig', this.app)
      flowStore.setTimerOptions({})
      this.triggerContentKey = uuid()
    },
    getTimerOptions() {
      return this.$refs.triggerDrawerDom?.getTimerOptions()
    }
  },
  components:{
    [SearchTree.name]:SearchTree,
    triggerContent
  }
}
</script>
<style lang="scss" scoped>
.template-content{
  background: #F5F5F5;
  border-radius: 4px;
  overflow-y: auto;
  padding: 20px;
  .system-message-template{
    padding: 10px 0 10px 16px;
    border-radius: 4px;
    background-color: #fff;
    width: 350px;
    h3{
      margin-bottom: 0;
    }
    .desc{
      font-size: 13px;
    }
    .template-content-item{
      font-size: 14px;
      line-height: 24px;
    }
    .date{
      margin-top: 20px;
    }
  }
}
</style>
